﻿using System;
using System.Collections.Generic;
using System.Linq;
using HappyBa.Core.Data;
using HappyBa.Core.Interfaces;

namespace HappyBa.Core.Statistics
{
    public class JobCodeTimeCalculator : IStatisticsCalculator
    {
        public IEnumerable<string> Calculate(StatisticsContext context)
        {
            var tasksByJobCode = context.Metrics.EstimatableEntities.GroupBy(x => GetJobCodeField(x) == null ? null : GetJobCodeField(x).Value).Where(x => !string.IsNullOrEmpty(x.Key));
            foreach (var job in tasksByJobCode)
            {
                var code = GetJobCodeField(job.First());
                var estimated = job.Sum(x => x.Effort);
                var done = job.Sum(x => x.TimeSpent);
                var progress = estimated == 0 ? 0 : (done / estimated * 100);
                yield return string.Format("[{0}] - progress - {1:0.##}/{2:0.##} ({3:0.##}%)", code.Value, done, estimated, progress) ;
            }
        }
        private static CustomField GetJobCodeField(UIEstimatableEntityBase entity)
        {
            var field = entity.CustomFields
                    .Where(x => string.Equals("job", x.Name, StringComparison.OrdinalIgnoreCase) || string.Equals("Job (more)", x.Name, StringComparison.OrdinalIgnoreCase))
                    .FirstOrDefault(x => !string.IsNullOrEmpty(x.Value));
            return field;
        }
    }
}
